<script setup lang="ts">
import { ref, watch } from "vue";
import { ButtonsCallBackParams, PlusColumn } from "plus-pro-components";

defineOptions({
  name: "JsonEditor"
});

const props = defineProps({
  search_config: {
    type: Object
  }
});

const data = ref<any>({});
const rowIndex = ref(0);
watch(
  () => props.search_config,
  () => {
    data.value = props.search_config;
  }
);
const tableConfig = ref<PlusColumn[]>([
  {
    label: "code值",
    prop: "prop"
  },
  {
    label: "展示值",
    prop: "label"
  },
  {
    label: "表格列宽",
    prop: "width"
  },
  {
    label: "表格列最小宽",
    prop: "minWidth"
  },
  {
    label: "值的类型",
    prop: "valueType"
  },
  {
    label: "排序",
    prop: "order",
    valueType: "input-number"
  }
]);

const buttons = [
  {
    text: "编辑",
    code: "update",
    props: { type: "success" },
    onClick(params: ButtonsCallBackParams) {
      values.value = { ...params.row };
      visible.value = true;
      rowIndex.value = params.rowIndex;
    }
  },
  {
    text: "删除",
    code: "delete",
    confirm: true,
    props: { type: "warning" },
    onConfirm(params: ButtonsCallBackParams) {
      data.value.columns.splice(params.rowIndex, 1);
    }
  },
  {
    text: "复制",
    code: "view",
    props: { type: "info" },
    onClick(params: ButtonsCallBackParams) {
      data.value.columns.push(params.row);
    }
  }
];

const visible = ref(false);
const values = ref({});

function handleConfirm() {
  visible.value = false;
  sort(rowIndex.value, values.value);
}

function sort(index: number, value: any) {
  data.value.columns.splice(index, 1);
  const order = value.order;
  for (let i = 0; i < data.value.columns.length; i++) {
    const item = data.value.columns[i];
    if (item.order < order) {
      data.value.columns.splice(i, 0, value);
      return;
    }
  }
  data.value.columns.splice(data.value.columns.length, 0, value);
}
</script>

<template>
  <div>
    <PlusTable
      :columns="tableConfig"
      :table-data="data.columns"
      :action-bar="{
        buttons: buttons,
        type: 'link',
        width: 260
      }"
      :default-sort="{ prop: 'order', order: 'descending' }"
    />
  </div>
  <PlusDrawerForm
    v-model:visible="visible"
    v-model="values"
    :form="{ columns: tableConfig }"
    @confirm="handleConfirm"
  />
</template>

<style scoped lang="scss"></style>
